<?php

namespace app\admin\controller\salary;

use app\common\controller\Backend;
use app\admin\model\SalaryBenchmarkItem;
use app\admin\model\SalaryBenchmarkData;
use app\admin\model\CourseType;
use app\admin\model\AdminSalaryBenchmarkItem;
use app\admin\model\WorkTemplate;
use think\Db;
/**
 * 工资基准项管理
 *
 * @icon fa fa-circle-o
 */
class SalaryBenchmark extends Backend
{

    /**
     * SalaryBenchmark模型对象
     * @var \app\admin\model\SalaryBenchmark
     */
    protected $model = null;
    const P_TYPE = 1;  //基准项
    const R_TYPE = 2;  //日常课程
    const D_TYPE = 3;  //代课
    const W_TYPE = 4;

    const N_TYPE = 9; // 新加类型

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\SalaryBenchmark;
        $staff_type = $this->model->getStaffTypeList();
        $this->view->assign("staff_type", $staff_type);
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = false;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model

                ->where($where)
                ->order('count_type', 'asc')
                ->paginate($limit);

            foreach ($list as $row) {
                $row->visible(['id','title','staff_type','count_type','create_time']);

            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                Db::startTrans();
                try {
                    $staff_type_arr = [];
                    $salary_info = $this->model->get(['title' => $params['title']]);
                    if (!empty($salary_info)) exception('该工资基准项已被添加');

                    $validate = $this->validate($params, 'SalaryBenchmark.add');
                    if ($validate !== true) exception($validate);

                    if ($params['count_type'] == 1) {
                        $num_price = sprintf('%.2f', $params['num_price']);
                        if ($num_price < 0) {
                            exception('次数单价不能小于0');
                        }
                    } else {
                        $staff_type_arr = json_decode($params['staff_type_arr'], true);
                        foreach ($staff_type_arr as &$v) {
                            if(!$v['name'])exception('单选项不能为空');
                            $v['price'] = sprintf('%.2f', $v['price']);
                            if ($v['price'] <= 0) exception('单选项费用不能小于0');
                        }
                        unset($params['num_price']);
                    }

                    $result = $this->model->allowField(true)->save($params);
                    if (!$result) exception('添加失败');

                    // 获取新增的ID
                    $id = $this->model->id;

                    // 保存关联的子项数据
                    if ($params['count_type'] == 2) {
                        $SalaryBenchmarkItem = new SalaryBenchmarkItem();
                        foreach ($staff_type_arr as &$v) {
                            $v['salary_benchmark_id'] = $id;
                        }
                        $res = $SalaryBenchmarkItem->saveAll($staff_type_arr);
                        if (!$res) exception('保存子项失败');
                    }
                    // 提交事务
                    Db::commit();
                } catch (\Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                $this->success();
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }

        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                Db::startTrans();
                try {

                    $admin_salary_count = Db::table('b_auth_asbi_template_item')->where('salary_benchmark_id',$ids)->count();
                    if($admin_salary_count > 0)exception('该自定义工资基准项已被选择');

//                    $admin_salary_count = AdminSalaryBenchmarkItem::where('salary_benchmark_id',$ids)->count();
//                    if($admin_salary_count > 0)exception('该自定义工资基准项已被员工选择不能修改');

                    $staff_type_arr = [];
                    $salary_info = $this->model->get(['title' => $params['title'],'id'=>['<>',$ids]]);
                    if (!empty($salary_info)) exception('该工资基准项已被添加');

                    $validate = $this->validate($params, 'SalaryBenchmark.add');
                    if ($validate !== true) exception($validate);

                    if ($params['count_type'] == 1) {
                        $num_price = sprintf('%.2f', $params['num_price']);
                        if ($num_price < 0) {
                            exception('次数单价不能小于0');
                        }
                    } else {
                        $staff_type_arr = json_decode($params['staff_type_arr'], true);
                        foreach ($staff_type_arr as &$v) {
                            if(!$v['name'])exception('单选项不能为空');
                            $v['price'] = sprintf('%.2f', $v['price']);
                            if ($v['price'] <= 0) exception('单选项费用不能小于0');
                        }
                        unset($params['num_price']);
                    }

                    $result = $row->allowField(true)->save($params);
                    if ($result === false) exception('修改失败');

                    $id = $row->id;
                    // 保存关联的子项数据
                    if ($params['count_type'] == 2) {
                        SalaryBenchmarkItem::where('salary_benchmark_id',$ids)->delete();
                        $SalaryBenchmarkItem = new SalaryBenchmarkItem();
                        foreach ($staff_type_arr as &$v) {
                            if(!$v['id']){
                                unset($v['id']);
                            }
                            $v['salary_benchmark_id'] = $id;
                            $res = $SalaryBenchmarkItem->insert($v);
                            if ($res === false) exception('保存子项失败');
                        }
//                        dump($staff_type_arr);exit;
                    }
                    // 提交事务
                    Db::commit();
                } catch (\Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                $this->success();
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $SalaryBenchmarkItemInfo = SalaryBenchmarkItem::where('salary_benchmark_id',$ids)->select();
        $item_arr = [];
        foreach ($SalaryBenchmarkItemInfo as $v){
            $arr = array('name'=>$v['name'],'price'=>$v['price'],'id'=>$v['id']);
            array_push($item_arr,$arr);
        }
        $this->view->assign("item_arr", json_encode($item_arr));
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    /**
     * 查看详情
     */
    public function show_detail($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }

        if ($this->request->isPost()) {

        }
        $SalaryBenchmarkItemInfo = SalaryBenchmarkItem::where('salary_benchmark_id',$ids)->select();
        $item_arr = [];
        foreach ($SalaryBenchmarkItemInfo as $v){
            $arr = array('name'=>$v['name'],'price'=>$v['price']);
            array_push($item_arr,$arr);
        }
        $this->view->assign("item_arr", json_encode($item_arr));
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }



    /**
     * 删除
     */
    public function del($ids = "")
    {
        if (!$this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ? $ids : $this->request->post("ids");
        if ($ids) {
            try {
                $admin_salary_count = Db::table('b_auth_asbi_template_item')->where('salary_benchmark_id',$ids)->count();
                if($admin_salary_count > 0)exception('该自定义工资基准项已被选择');
                if(Db::table('b_salary_benchmark_data')->where('salary_benchmark_id',$ids)->count()){
                    exception(__('该自定义工资基准项已被选择'));
                }
//                $admin_salary_count = AdminSalaryBenchmarkItem::where('salary_benchmark_id',$ids)->count();
//                if($admin_salary_count > 0)exception('该自定义工资基准项已被员工选择');
                //同步删除导入数据
                SalaryBenchmarkData::where('salary_benchmark_id',$ids)->delete();
                SalaryBenchmarkItem::where('salary_benchmark_id',$ids)->delete();
                $this->model->whereIn('id',$ids )->delete();
            } catch (\Exception $e) {
                $this->error($e->getMessage());
            }
            $this->success();
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }

    /**
     * 获取基准项
     */
    public function get_template()
    {
        $type = $this->request->param('type',1);
        $list = $this->model
            ->field('id,title')
            ->where(['staff_type'=>$type])
            ->order('id','desc')
            ->select();

        foreach ($list as &$v){
            $v['type'] = self::P_TYPE;
            $v['identifying'] = $v['id'].'-'.$v['type'];//计算公式标识
        }
        if($type == 1){
//            $course_type_list = CourseType::field('id,name as title,type')->select();
//            foreach ($course_type_list as &$v){
//                if($v['type'] == 2){
//                    $type = self::D_TYPE;
//                    $v['title'] = '代课课程-'.$v['title'].'次';
//                }else{
//                    $type = self::R_TYPE;
//                    $v['title'] = '日常课程-'.$v['title'].'次';
//                }
//                $v['identifying'] = $v['id'].'-'.$type;
//            }
//            $list = array_merge($list,$course_type_list);
            $course_type_list = [
                [
                    'id' => 999,
                    'title' => '主科-课时费用',
                    'type'=>self::N_TYPE,
                    'identifying' => '999-11',
                ],[
                    'id' => 999,
                    'title' => '主科-代课费用',
                    'type'=>self::N_TYPE,
                    'identifying' => '999-12',
                ],[
                    'id' => 999,
                    'title' => '主科-被代课费用',
                    'type'=>self::N_TYPE,
                    'identifying' => '999-13',
                ],[
                    'id' => 999,
                    'title' => '科任-课时费用',
                    'type'=>self::N_TYPE,
                    'identifying' => '999-14',
                ],[
                    'id' => 999,
                    'title' => '科任-代课费用',
                    'type'=>self::N_TYPE,
                    'identifying' => '999-15',
                ],[
                    'id' => 999,
                    'title' => '科任-被代课费用',
                    'type'=>self::N_TYPE,
                    'identifying' => '999-16',
                ],[
                    'id' => 999,
                    'title' => '班队会-课时费用',
                    'type'=>self::N_TYPE,
                    'identifying' => '999-17',
                ],[
                    'id' => 999,
                    'title' => '班队会-代课费用',
                    'type'=>self::N_TYPE,
                    'identifying' => '999-18',
                ],[
                    'id' => 999,
                    'title' => '班队费-被代课费用',
                    'type'=>self::N_TYPE,
                    'identifying' => '999-19',
                ]
            ];

            // 以下id各代表  1 分餐  2 看班  3 社团
            $type_arr = (new WorkTemplate())->type_arr;
            $work_arr = [];
            foreach ($type_arr as $k => &$v){
                if($k == 3)$v = '社团主教';
                $arr = array(
                    'id' => $k,
                    'title' => $v.'费用',
                    'type'=>self::W_TYPE,
                    'identifying' => $k.'-'.self::W_TYPE,
                );

                array_push($work_arr,$arr);
            }
//            $work_arr[] = array(
//                'id' => 3,
//                'title' => '社团助教次',
//                'type'=>5,
//                'identifying' => '3-5',
//            );
            $work_arr[] = array(
                'id' => 999,
                'title' => '值班白班费用',
                'type'=>self::N_TYPE,
                'identifying' => '999-1',
            );
            $work_arr[] = array(
                'id' => 999,
                'title' => '值班夜班费用',
                'type'=>self::N_TYPE,
                'identifying' => '999-2',
            );
            $work_arr[] = array(
                'id' => 999,
                'title' => '值班夜宿班费用',
                'type'=>self::N_TYPE,
                'identifying' => '999-3',
            );
            $work_arr[] = array(
                'id' => 999,
                'title' => '社团费用',
                'type'=>self::N_TYPE,
                'identifying' => '999-4',
            );
            $work_arr[] = array(
                'id' => 999,
                'title' => '课业辅导费用',
                'type'=>self::N_TYPE,
                'identifying' => '999-5',
            );

            $work_arr[] = array(
                'id' => 999,
                'title' => '护导费用',
                'type'=>self::N_TYPE,
                'identifying' => '999-6',
            );
            $work_arr[] = array(
                'id' => 999,
                'title' => '代班主任费用',
                'type'=>self::N_TYPE,
                'identifying' => '999-7',
            );
            $work_arr[] = array(
                'id' => 999,
                'title' => '被代班主任费用',
                'type'=>self::N_TYPE,
                'identifying' => '999-8',
            );
            $list = array_merge($list,$course_type_list,$work_arr);

        }
        return json(array('code'=>'1','msg'=>'ok','data'=>$list));
    }

}
